package com.xhh.nphm.system.service.impl;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.common.utils.sms.SmsUtils;
import com.xhh.nphm.system.service.ISmsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements ISmsService {

    @Value("${sms.enableSmsCode}")
    private boolean enable;

    private static final String sendStatusOK = "success";

    private static final Cache<String, Object> build = Caffeine.newBuilder()
            .expireAfterWrite(3, TimeUnit.MINUTES) //过期时间
            .build();

    private static final Cache<String, Object> againTime = Caffeine.newBuilder()
            .expireAfterWrite(1, TimeUnit.MINUTES) //再次获取验证码间隔时间
            .build();

    @Override
    public String getSmsCode(String mobile) {
        String status = SmsUtils.sendStatusFail;
        if (SmsUtils.isMobile(mobile)) {
            Object smsCodeCache = build.getIfPresent(mobile);
            Object isReacquire = againTime.getIfPresent(mobile);
            if(isReacquire != null){
                return SmsUtils.sendStatusForbidden;
            }
            String smsCode = SmsUtils.generateCode();
            if (smsCodeCache == null || !smsCodeCache.equals(mobile)) {
                System.out.println("短信验证码：" + smsCode);
                boolean result = true;
                if(enable){
                    result  = SmsUtils.sendSmsCode(mobile, smsCode);
                }
                if (result) {
                    status = SmsUtils.sendStatusOK;
                    build.put(mobile,smsCode);
                    againTime.put(mobile,new Date());
                } else {
                    status =  SmsUtils.sendStatusFail;
                }
            } else {
                status = SmsUtils.sendStatusFail;
            }
        } else {
            status = SmsUtils.sendStatusError;
        }
        return status;
    }


    @Override
    public String verifySMSCode(String mobile,String inputCode) {
        String status = SmsUtils.verifyStatusFail;
        Object cache = build.getIfPresent(mobile);
        if ((StringUtils.isNotBlank(mobile)) && (cache != null)) {
            String oldSmsCode = cache.toString();
            if ((StringUtils.isNotEmpty(inputCode)) && (inputCode.equals(oldSmsCode))) {
                status = SmsServiceImpl.sendStatusOK;
                build.invalidate(mobile);
                againTime.invalidate(mobile);
            }
        }
        return status;
    }
}
